from django.shortcuts import render, HttpResponse, redirect
from django.http import FileResponse, Http404
from excleapp.word.main import main,Semester_courses,Course_proportions,Create_Matrix,Create_Supporting_Course, Find_semester, Find_Course_proportions
from excleapp.word.WordDBUse import DbUse
import os
dbuse = DbUse()
dbuse.initdata()
file_path = 'excleapp/word/template/湘南学院/计算机科学与技术/123_2022mid.docx'
find_year = None

find_major = None

edition = 1





def find_course_form(request):
    print(find_year)
    year = dbuse.selectcoursetemplates_year(edition)
    semester = Find_semester('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid, year)
    course = Find_Course_proportions('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid, year)
    max_kaoshi = 0
    max_kaocha = 0
    max_other = 0
    l_kaoshi = []
    l_kaocha = []
    l_other = []
    for item in semester:
        max_kaoshi = max(max_kaoshi, len(item['kaoshi']))
        max_kaocha = max(max_kaocha, len(item['kaocha']))
        max_other = max(max_other, len(item['otherclass']))
    for item in semester:
        l_kaoshi.append(max_kaoshi - len(item['kaoshi']))
        l_kaocha.append(max_kaocha - len(item['kaocha']))
        l_other.append(max_other - len(item['otherclass']))
    info = zip(semester, l_kaoshi, l_kaocha, l_other)
    return render(request, "course_form.html",
                  {"max_kaoshi": max_kaoshi, "course": course, "max_kaocha": max_kaocha, "max_other": max_other,
                   "info": info})



def new_matrix(request):
    data = dbuse.selectmatrix_year(2022)
    info = zip(data)
    print(dbuse.userid)
    return render(request,"new_matrix.html",{"info":info})



def course_form(request):
    year=dbuse.selectcoursetemplates_year(edition)['year']
    semester=Semester_courses('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid,year)
    course=Course_proportions('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid,year)
    max_kaoshi=0
    max_kaocha=0
    max_other=0
    l_kaoshi=[]
    l_kaocha=[]
    l_other=[]
    for item in semester:
        max_kaoshi=max(max_kaoshi, len(item['kaoshi']))
        max_kaocha=max(max_kaocha, len(item['kaocha']))
        max_other = max(max_other, len(item['otherclass']))
    for item in semester:
        l_kaoshi.append(max_kaoshi-len(item['kaoshi']))
        l_kaocha.append(max_kaocha-len(item['kaocha']))
        l_other.append(max_other - len(item['otherclass']))
    sum_credit = 0
    sum_period = 0
    for item in course:
        sum_credit += float(course[item]['credit'])
        sum_period += float(course[item]['period'])
    print(find_major)
    info=zip(semester,l_kaoshi,l_kaocha,l_other)
    return render(request, "course_form.html", {"max_kaoshi":max_kaoshi,"course":course, "max_kaocha":max_kaocha, "max_other":max_other, "info":info, "sum_credit":sum_credit, "sum_period":sum_period, "year":year, "major":find_major})


def register(request):
    return render(request, "register.html")

def login(request):
    # yaer = dbuse.selectcoursetemplates_year(edition)
    # file_path = 'excleapp/word/template/湘南学院/计算机科学与技术/'+str(dbuse.userid)+'_'+str(yaer)+'mid.docx'

    if (os.path.isfile(file_path)):
        os.remove(file_path)
    if request.method == "GET":
        return render(request, "login.html")


    try:
        dbuse.userid = int(request.POST["userid"])
        password = request.POST["password"]
        user = dbuse.selectuserdictinfo(dbuse.userid)

        global find_major
        find_major = dbuse.selectuserdictinfo(dbuse.userid)['major']
        print(find_major)

        if dbuse.userid== user["userid"] :
            if password ==  user["password"]:
                return redirect("/upcourse/")
            return render(request, "login.html", {"tip": "密码错误。。。"})
        return render(request, "login.html",{"tip":"账号错误。。。"})
    except KeyError:
        return render(request, "login.html")

def registered(request):
    if request.method == "GET":
        return render(request, "register.html", {"isexist": False})
    try:
        dbuse.userid = int(request.POST["userid"])
        name = request.POST["name"]
        password = request.POST["password"]
        major = request.POST["major"]
        if dbuse.selectuserdictinfo(dbuse.userid) == -1:
            dbuse.insertuser(dbuse.userid, name, password, major)
            return redirect("/login/")
        return render(request, "register.html", {"isexist": True})
    except Exception as result:
        print("位置异常为：%s"%result)
        return render(request, "register.html", {"isexist": True})


def index(request):
    return render(request, "index.html")


# def upcourse(request):
#
#     info = dbuse.selectcoursetemplates_path()  #数据接口，每一组的第一个数据是他的序号,第二个数据是年份
#
#     if request.method == "GET":
#         # if (os.path.isfile(file_path)):
#         #     os.remove(file_path)
#         userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
#         if (os.path.isfile(file_path)):
#             return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
#         return render(request, "upload.html",{"major": userdictinfo["major"]})
#     if request.method == "POST":
#         userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
#         if (os.path.isfile(file_path)):
#             return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
#         return render(request, "upload.html",{"major": userdictinfo["major"]})

# def upcourse(request):
#     # info = dbuse.selectcoursetemplates_path()  # 数据接口，每一组的第一个数据是他的序号,第二个数据是年份
#     if request.method == "GET":
#         # if (os.path.isfile(file_path)):
#         #     os.remove(file_path)
#         userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
#         if (os.path.isfile(file_path)):
#             return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
#         # return render(request, "upload.html",{"major": userdictinfo["major"], "userid":userdictinfo["userid"], "info":info})
#         return render(request, "upload.html", {"major": userdictinfo["major"],"userid": userdictinfo["userid"]})
#     if request.method == "POST":
#         userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
#         if (os.path.isfile(file_path)):
#             return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
#         return render(request, "upload.html",{"major": userdictinfo["major"],"userid": userdictinfo["userid"]})

def upcourse(request):
    # yaer = dbuse.selectcoursetemplates_year(edition)
    # file_path = 'excleapp/word/template/湘南学院/计算机科学与技术/' + str(dbuse.userid) + '_' + str(yaer) + 'mid.docx'
    info = dbuse.selectcoursetemplates_path()  # 数据接口，每一组的第一个数据是他的序号,第二个数据是年份
    print(info)
    print(dbuse.userid)
    if request.method == "GET":
        # if (os.path.isfile(file_path)):
        #     os.remove(file_path)
        userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
        if (os.path.isfile(file_path)):
            return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
        return render(request, "upload.html",{"major": userdictinfo["major"], "userid":userdictinfo["userid"], "info": info, "info_length":len(info)})
    if request.method == "POST":

        global edition
        if request.POST['edition'] != None:
            edition = request.POST['edition']
        userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
        if (os.path.isfile(file_path)):
            return render(request, "upload.html", {"isupload": "培养方案自动生成成功......"})
        return render(request, "upload.html",{"major": userdictinfo["major"], "userid":userdictinfo["userid"], "info": info, "info_length":len(info)})

def submitcourse(request):
    '''上传（Excle文件）'''
    if request.method == 'POST':
        # try:
        global find_year
        find_year = request.POST['year']
        print(find_year)
        print(dbuse.userid)
        dbuse.insertcoursetemplates(find_year)
        coursetemplatesdictinfo = dbuse.selectcoursetemplates(find_year)
        print(coursetemplatesdictinfo, "666")
        file_object = request.FILES.get("exc")
        # print(type(file_object))
        # print(file_object.name)  # 文件名

        f = open(coursetemplatesdictinfo.get('coursepath'), mode="wb")
        for chunk in file_object.chunks():
            f.write(chunk)
        f.close()
        user = dbuse.selectuserdictinfo(dbuse.userid)
        dbuse.LoadCourse(file_object, user["userid"], user["name"], user["password"], user["major"])
        main('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid,find_year)

        return redirect("/upcourse/")
        # except Exception as result:
        #     print('未知异常：%s'%result)
        #     return render(request, "upload.html")

def find_word(request):
    '''上传（Excle文件）'''
    if request.method == 'POST':
        # try:
        global find_year
        find_year = request.POST['up_year']

        # dbuse.insertcoursetemplates(year)
        # coursetemplatesdictinfo = dbuse.selectcoursetemplates(year)
        # coursetemplates_path = coursetemplatesdictinfo.get('coursepath')
        # print(coursetemplatesdictinfo, "666")
        # file_object = request.FILES.get("exc")
        #     # print(type(file_object))
        #     # print(file_object.name)  # 文件名
        # f = open(coursetemplates_path, mode="wb")
        # for chunk in file_object.chunks():
        #     f.write(chunk)
        # f.close()
        # user = dbuse.selectuserdictinfo(dbuse.userid)
        # dbuse.LoadCourse(file_object, user["userid"], user["name"], user["password"], user["major"])
        main('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid,find_year)
        return redirect("/upcourse/")
            # except Exception as result:
            #     print('未知异常：%s'%result)
            #     return render(request, "upload.html")


def download_word(request):
    try:
        yaer = dbuse.selectcoursetemplates_year(edition)
        file_path = 'excleapp/word/template/湘南学院/计算机科学与技术/' + str(dbuse.userid) + '_' + str(yaer['year']) + 'mid.docx'
        response = FileResponse(open(file_path, 'rb'))
        # response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('course.xls'))
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format('mid.docx').encode('utf-8', 'ISO-8859-1')
        response['content_type'] = "application/octet-stream"
        return response
    except Exception as result:
        print("未知异常%s" % result)
        raise Http404

# def find_word(request):
#     try:
#         find_year = request.POST['up_year']
#

def download_Matrix(request):
    try:
        year = dbuse.selectcoursetemplates_year(edition)
        path=Create_Matrix("template/湘南学院/计算机科学与技术/",str(dbuse.userid),year['year'])
        response = FileResponse(open(path, 'rb'))
        # response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('course.xls'))
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format('Matrix.xlsx').encode('utf-8', 'ISO-8859-1')
        response['content_type'] = "application/octet-stream"
        return response
    except Exception as result:
        print("未知异常%s" % result)
        raise Http404


def download_Supporting_Course(request):
    try:
        year = dbuse.selectcoursetemplates_year(edition)['year']
        info=dbuse.selectuserdictinfo(dbuse.userid)
        major = info["major"]
        path=Create_Supporting_Course("template/湘南学院/计算机科学与技术/",str(dbuse.userid),major,year)
        response = FileResponse(open(path, 'rb'))
        # response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('course.xls'))
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format('Supporting_Course.docx').encode('utf-8', 'ISO-8859-1')
        response['content_type'] = "application/octet-stream"
        return response
    except Exception as result:
        print("未知异常%s" % result)
        raise Http404



def download_coursetemplates(request):
    try:

        coursetemplatesdictinfo = dbuse.selectcoursetemplates_a()
        # if coursetemplatesdictinfo != -1:
        if(os.path.isfile(coursetemplatesdictinfo.get('coursepath'))):
            response = FileResponse(open(coursetemplatesdictinfo.get('coursepath'), 'rb'))
        else:
            response = FileResponse(open('excleapp/word/template/湘南学院/coursetemplates.xlsx', 'rb'))
        # response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path('course.xls'))

        response['Content-Disposition'] = 'attachment;filename="{0}"'.format('course.xlsx').encode('utf-8',
                                                                                                            'ISO-8859-1')
        response['content_type'] = "application/octet-stream"
        return response
    except Exception as result:
        print('未知异常：%s' % result)
        raise Http404


def information(request):
    yaer = dbuse.selectcoursetemplates_year(edition)
    file_path = 'excleapp/word/template/湘南学院/计算机科学与技术/' + str(dbuse.userid) + '_' + str(yaer['year']) + 'mid.docx'
    if (os.path.isfile(file_path)):
        os.remove(file_path)
    if request.method == "GET":
        userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
        templates = dbuse.selecttemplatesdict(userdictinfo["major"])
        majors = dbuse.selectcoursetemplatesslist()
        print(majors)
        return render(request, "information.html",
                      {"educationalObjectives": templates["目标"], "educationRequirement": templates["要求"],
                       "trainingExpected": templates["预期"], "mainSubjects": templates["主干学科"],
                       "mainPracticeTeachingLinks": templates["主要实践性教学环节"],
                       "professionalCoreCourses": templates["专业核心课程"], "majors": majors,
                       "major": userdictinfo["major"]})
    try:
        input_mainSubjects = request.POST['mainSubjects']
        input_mainSubjects = input_mainSubjects.strip('\n')
        input_mainPracticeTeachingLinks = request.POST['mainPracticeTeachingLinks']
        input_mainPracticeTeachingLinks = input_mainPracticeTeachingLinks.strip('\n')
        input_professionalCoreCourses = request.POST['professionalCoreCourses']
        input_professionalCoreCourses = input_professionalCoreCourses.strip('\n')
        input_educationalObjectives = request.POST['educationalObjectives']
        input_educationalObjectives = input_educationalObjectives.strip('\n')
        input_educationRequirement = request.POST['educationRequirement']
        input_educationRequirement = input_educationRequirement.strip('\n')
        input_trainingExpected = request.POST['trainingExpected']
        input_trainingExpected = input_trainingExpected.strip('\n')
        # input_courseCodeRule = request.POST['courseCodeRule']
        userdictinfo = dbuse.selectuserdictinfo(dbuse.userid)
        print([input_educationalObjectives, input_educationRequirement, input_trainingExpected, input_mainSubjects,
               input_mainPracticeTeachingLinks, input_professionalCoreCourses])
        dbuse.inserttemplates(userdictinfo["major"],
                              [input_educationalObjectives, input_educationRequirement, input_trainingExpected,
                               input_mainSubjects,
                               input_mainPracticeTeachingLinks, input_professionalCoreCourses])
        return redirect("/upcourse/")
    except KeyError:
        return redirect("/upcourse/")

def upmajor(request):
    if request.method == "POST":
        input_major = request.POST["inputmajor"]
        dbuse.updateusermajor(dbuse.userid, input_major)
        return redirect("/information/")


def generated(request):
    if request.method == "GET":
        try:
            coursetemplatesdictinfo = dbuse.selectcoursetemplates()
            if (os.path.isfile(coursetemplatesdictinfo.get('coursepath'))):
                main('excleapp/word/template/湘南学院/计算机科学与技术/', dbuse.userid)
                return redirect("/upcourse/")
            return redirect("/upcourse/")
        except Exception as result:
            print("未知异常为%s"%(result))
            return redirect("/upcourse/")